package com.sakura.mybatis.executor;

import com.sakura.mybatis.config.BoundSql;
import com.sakura.mybatis.config.Configuration;
import com.sakura.mybatis.config.MappedStatement;
import com.sakura.mybatis.utils.GenericTokenParser;
import com.sakura.mybatis.utils.NamingConverter;
import com.sakura.mybatis.utils.ParameterMapping;
import com.sakura.mybatis.utils.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SimpleExecutor implements Executor {

    private Connection connection;

    private PreparedStatement preparedStatement;

    private ResultSet resultSet;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object param) {
        DataSource dataSource = configuration.getDataSource();
        List<E> resultList = new ArrayList<>();
        try {

            BoundSql boundSql = getBoundSql(mappedStatement.getSql());

            connection = dataSource.getConnection();

            preparedStatement = connection.prepareStatement(boundSql.getFinalSql());
            // 如果有参数，设置参数
            if (param != null) {
                List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
                // 参数类型
                String parameterType = mappedStatement.getParameterType();
                int index = 0;
                for (ParameterMapping parameterMapping : parameterMappingList) {
                    Class<?> parameterClass = Class.forName(parameterType);
                    Field field = parameterClass.getDeclaredField(parameterMapping.getContent());
                    field.setAccessible(true);
                    Object value = field.get(param);
                    // 设置值下标必须从1开始
                    preparedStatement.setObject(++index, value);
                }
            }
            resultSet = preparedStatement.executeQuery();
            Class<?> resultType = Class.forName(mappedStatement.getResultType());
            while (resultSet.next()) {
                // 创建结果对象
                E resultObject = (E) resultType.getDeclaredConstructor().newInstance();
                // 映射字段
                // 获取DB元数据
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                // 获取值下标必须从1开始
                for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                    // 获取DB一行数据的列名
                    String dbColumnName = resultSetMetaData.getColumnName(i);
                    // db列名转驼峰 user_name -> userName
                    String columnName = NamingConverter.underlineToCamel(dbColumnName);
                    // 属性描述器，可以获取指定字段的读写方法
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    // 获取该字段的实际Java类型
                    Class<?> propertyType = propertyDescriptor.getPropertyType();
                    // 获取对应字段的类型结果（会从jdbc类型转换为java类型）
                    Object value = resultSet.getObject(dbColumnName, propertyType);
                    writeMethod.invoke(resultObject, value);
                }
                resultList.add(resultObject);
            }
            return resultList;
        } catch (Exception e) {
            throw new RuntimeException("executor execute query error", e);
        }
    }

    private BoundSql getBoundSql(String sql) {
        // 用于记录#{}中的内容
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 将#{}解析成？
        String finalSql = genericTokenParser.parse(sql);
        // 比如#{id}就记录的id
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(finalSql, parameterMappings);
    }

    @Override
    public void close() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException("resultSet close error");
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new RuntimeException("preparedStatement close error");
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("connection close error");
            }
        }
    }
}
